package com.app.mingluxing.widget;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.ProviewAdapter;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.BitmapDetail;
import com.app.mingluxing.photoview.PhotoView;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * 预览图片页面
 * Created by Aaron on 15/8/18.
 */
public class PreviewPhotoActivity extends BaseActivity {

    private DisplayImageOptions options;
    private android.widget.TextView tvcurrentIndex;
    private android.widget.TextView tvtotal;
    private ArrayList<String> preUrlPhotos;
    private List<BitmapDetail> details;
    //    private android.widget.RelativeLayout rlshow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.widget_photo_view);

        initWidget();

        //当前预览图片的角标
        int position = getIntent().getIntExtra("position", 0);

        //本地图片的集合
        details = (List<BitmapDetail>) getIntent().getSerializableExtra("lists");

        //网络图片的集合
        preUrlPhotos = getIntent().getStringArrayListExtra("preUrlPhotos");

        List<PhotoView> photoviews = new ArrayList<PhotoView>();

        if (details != null) { //本地图片的预览

            tvtotal.setText(details.size() + "");

            for (BitmapDetail b : details) {

                PhotoView photoView = new PhotoView(this);
                photoView.setImageBitmap(CommonUtils.getBitmapFromPath(b.mPath));
                photoviews.add(photoView);

            }

        } else if (preUrlPhotos != null) {//网络图片的预览

            options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.icon_loading_big_default)
                    .showImageForEmptyUri(R.drawable.icon_default)
                    .showImageOnFail(R.drawable.icon_default)
                    .resetViewBeforeLoading(true)
                    .cacheOnDisk(true).cacheInMemory(true)
                    .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .considerExifParams(true)
                    .displayer(new SimpleBitmapDisplayer()).build();
//
            tvtotal.setText(preUrlPhotos.size() + "");

            for (String b : preUrlPhotos) {

                PhotoView photoView = new PhotoView(this);
                // 朋友圈大图  + _Tb
                ImageLoader.getInstance().displayImage(b, photoView, options);
                photoviews.add(photoView);

            }

        }

        tvcurrentIndex.setText((position + 1) + "");

        ProviewAdapter proviewAdapter = new ProviewAdapter(photoviews, this);

        ViewPager vp_pics = (ViewPager) findViewById(R.id.vp_pics);

        vp_pics.setAdapter(proviewAdapter);
        vp_pics.setCurrentItem(position);

        vp_pics.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                tvcurrentIndex.setText(++i + "");
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });

        EventBus.getDefault().register(this);

    }

    private void initWidget() {

//        this.rlshow = (RelativeLayout) findViewById(R.id.rl_show);
        this.tvtotal = (TextView) findViewById(R.id.tv_total);
        this.tvcurrentIndex = (TextView) findViewById(R.id.tv_currentIndex);

    }

    /**
     * 长按 保存图片 至本地
     */
    public void onEventMainThread(final Integer i) {

        if (preUrlPhotos == null || preUrlPhotos.size() == 0)
            return;

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("保存", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                //保存图片到本地
                                savePic2Local(preUrlPhotos.get(i));
                            }

                        }).show();

    }

    /**
     * 保存图片到本地
     * @param picUrl
     */
    private void savePic2Local(String picUrl) {

        final ProgressDialog show = ProgressDialog.show(this, "正在保存图片...", Constant.WAIT);
        ImageRequest imageRequest = new ImageRequest(picUrl,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
//                        imageView.setImageBitmap(response);

                        MediaStore.Images.Media.insertImage(getContentResolver(), response, "", "");

//                       final   MediaScannerConnection msc = new MediaScannerConnection(PreviewPhotoActivity.this, new MediaScannerConnection.MediaScannerConnectionClient() {
//                            public void onMediaScannerConnected() {
////                                msc.scanFile("/sdcard/image.jpg", "image/jpeg");
//                            }
//                            public void onScanCompleted(String path, Uri uri) {
//
////                                msc.disconnect();
//                            }
//                        });

                        showToast("保存成功");

                        response.recycle();
                        response = null;

                        if (show != null && show.isShowing())
                            show.dismiss();
                    }
                }, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (show != null && show.isShowing())
                    show.dismiss();
                showToast("保存失败");
//                imageView.setImageResource(R.drawable.default_image);
            }
        });

        mApplication.addToRequestQueue(imageRequest, getClass().getName());

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());
        EventBus.getDefault().unregister(this);

//        if (details!=null && details.size() > 0) {
//            for (int i = 0; i < details.size(); i++) {
//
//                details.get(i).mPath
//            }
//        }

    }

    @Override
    public void widgetClick(View v) {

    }
}